package com.ychong.library.view.imagebanner

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.ychong.library.R
import com.ychong.library.utils.ResUtils
import com.ychong.library.utils.ScreenUtils
import java.util.*


class ImageBannerView : FrameLayout, ViewPager.OnPageChangeListener {
    private var indicatorDotColor: Int
    private var isLoop: Boolean

    /**
     * 轮播切换小圆点宽度
     */
    private var indicatorDotSize: Int
    private var isShowSwitchDot: Boolean
    private var isAutoSwitch: Boolean

    /**
     * 当前banner需要显式的数量
     */
    private var mShowCount = 0
    private var mCurrentPosition = 0
    private var viewPager: ViewPager? = null
    private var carouselLayout: LinearLayout? = null
    private var adapter: IImageAdapter? = null

    /**
     * 用户是否干预
     */
    private var isUserTouched = false

    /**
     * 设置轮播时间
     */
    private var switchTime: Long = DEFAULT_TIME

    /**
     * 轮播图定时器
     */
    private var mTimer: Timer? = null

    companion object {
        private const val MSG = 0X100

        /**
         * 轮播图最大数
         */
        private var totalCount: Int = Int.MAX_VALUE

        /**
         * 默认的轮播时间
         */
        private const val DEFAULT_TIME: Long = 3000


    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
    constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(
        context,
        attributeSet,
        defStyle
    ) {
        val style = context.obtainStyledAttributes(
            attributeSet,
            R.styleable.YCHListImageBannerView,
            0,
            defStyle
        )
        isAutoSwitch = style.getBoolean(R.styleable.YCHListImageBannerView_ibvAutoSwitch, true)
        switchTime =
            style.getInteger(R.styleable.YCHListImageBannerView_ibvSwitchTime, 2000).toLong()
        isShowSwitchDot =
            style.getBoolean(R.styleable.YCHListImageBannerView_ibvShowSwitchDot, true)
        indicatorDotSize = style.getDimensionPixelSize(
            R.styleable.YCHListImageBannerView_ibvIndicatorDotSize,
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5f, resources.displayMetrics)
                .toInt()
        )
        indicatorDotColor = style.getColor(
            R.styleable.YCHListImageBannerView_ibvIndicatorDotColor,
            ResUtils.getColor(context, R.color.color_0D71DF)
        )
        isLoop = style.getBoolean(R.styleable.YCHListImageBannerView_ibvIsLoop, true)
        style.recycle()

        val view: View = LayoutInflater.from(context).inflate(R.layout.layout_carousel, null)
        val lp = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ScreenUtils.dpToPx(1000))
        viewPager = view.findViewById(R.id.gallery_vp)
        //viewPager!!.layoutParams = lp
        carouselLayout = view.findViewById(R.id.page_layout)
        viewPager!!.addOnPageChangeListener(this)
        addView(view)
    }

    @SuppressLint("ClickableViewAccessibility")
    fun init(dataList: MutableList<String>) {
        adapter = DefaultImageAdapter(context, dataList)
        mShowCount = adapter!!.getCount()

        viewPager!!.adapter = ViewPagerAdapter()
        viewPager!!.currentItem = 0
        startTimeTask()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var width = MeasureSpec.getSize(widthMeasureSpec)
        if (widthMode==MeasureSpec.EXACTLY){
            //wrap_content
            width = ScreenUtils.dpToPx(300)+paddingLeft+paddingRight
        }
        var height = MeasureSpec.getSize(heightMeasureSpec)
        if (heightMode == MeasureSpec.EXACTLY){
            //wrap_content
            height = ScreenUtils.dpToPx(500)+paddingTop+paddingBottom
        }
        setMeasuredDimension(width,height)
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE ->
                //有用户滑动事件发生
                isUserTouched = true
            MotionEvent.ACTION_UP -> isUserTouched = false
        }
        return false
    }

    /**启动定时*/
    private fun startTimeTask() {
        if (!isAutoSwitch) return
        //以指定周期定时任务
        mTimer = Timer()
        mTimer!!.schedule(mTimerTask, switchTime, switchTime)
    }
    fun cancelTimer() {
        mTimer?.cancel()
    }
    private val mTimerTask: TimerTask = object : TimerTask() {
        override fun run() {
            //用户滑动时，定时任务不响应
            if (!isUserTouched) {
                mCurrentPosition = (mCurrentPosition + 1) % totalCount
                mHandler.sendEmptyMessage(MSG)
            }
        }
    }
    @SuppressLint("HandlerLeak")
    val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == MSG) {
                if (mCurrentPosition == totalCount - 1) {
                    viewPager!!.setCurrentItem(mShowCount - 1, false)
                } else {
                    viewPager!!.currentItem = mCurrentPosition
                }
            }
        }

    }


    /**绘制切换小圆点*/
    private fun drawIndicatorDot() {
        if (!isShowSwitchDot) return
        carouselLayout!!.removeAllViews()
        //绘制切换小圆点
        for (i in 0 until mShowCount) {
            val v = carouselLayout!!.getChildAt(i)
            val view = v ?: View(context)
            if (mCurrentPosition % mShowCount == i) {
                view.isSelected = true
                //当前位置的点要绘制的较大一点，高亮显示
                val params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
                    indicatorDotSize + ScreenUtils.dpToPx(3),
                    indicatorDotSize + ScreenUtils.dpToPx(3)
                )
                params.setMargins(indicatorDotSize, 0, 0, 0)
                view.layoutParams = params
            } else {
                view.isSelected = false
                val params = LinearLayout.LayoutParams(indicatorDotSize, indicatorDotSize)
                params.setMargins(indicatorDotSize, 0, 0, 0)
                view.layoutParams = params
            }
            if (v == null) {
                view.setBackgroundColor(indicatorDotColor)
                carouselLayout!!.addView(view)
            }
        }

    }

    override fun onFinishInflate() {
        super.onFinishInflate()

    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    }

    override fun onPageSelected(position: Int) {
        mCurrentPosition = position
        drawIndicatorDot()
    }

    override fun onPageScrollStateChanged(state: Int) {
    }



    inner class ViewPagerAdapter : PagerAdapter() {
        override fun getCount(): Int {
            return totalCount
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view === `object`
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            var mPosition = position
            mPosition %= mShowCount
            val view: View = adapter!!.getView(mPosition)
            container.addView(view)
            return view
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }

        override fun getItemPosition(`object`: Any): Int {
            return super.getItemPosition(`object`)
        }

        override fun finishUpdate(container: ViewGroup) {
            super.finishUpdate(container)
            var position: Int = viewPager!!.currentItem
            if (position == 0) {
                position = mShowCount
                viewPager!!.setCurrentItem(position, true)
            } else if (position == totalCount - 1) {
                position = mShowCount - 1
                viewPager!!.setCurrentItem(position, true)
            }
        }
    }

    /**
     * 可自定义设置轮播图切换时间，单位毫秒
     */
    fun setSwitchTime(switchTime: Long) {
        this.switchTime = switchTime
    }

    /**设置是否自动切换*/
    fun isAutoSwitch(isAutoSwitch: Boolean) {
        this.isAutoSwitch = isAutoSwitch
    }

    /**设置切换小圆点大小*/
    fun setIndicatorDotSize(indicatorDotSize: Int) {
        this.indicatorDotSize = indicatorDotSize
    }
}